import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../core/auth_store.dart';
import '../utils/util.dart';

class AuthPage extends StatefulWidget {
  const AuthPage({super.key});

  @override
  State<AuthPage> createState() => _AuthPageState();
}

class _AuthPageState extends State<AuthPage> {
  int _tab = 0;
  final _loginPhoneController = TextEditingController();
  final _loginPasswordController = TextEditingController();
  final _regPhoneController = TextEditingController();
  final _regUsernameController = TextEditingController();
  final _regPasswordController = TextEditingController();
  bool _loading = false;

  @override
  void dispose() {
    _loginPhoneController.dispose();
    _loginPasswordController.dispose();
    _regPhoneController.dispose();
    _regUsernameController.dispose();
    _regPasswordController.dispose();
    super.dispose();
  }

  bool _isValidPhone(String s) => RegExp(r'^\d{11}$').hasMatch(s);
  bool _isValidUsername(String s) => RegExp(r'^[A-Za-z0-9_]{2,20}$').hasMatch(s);
  bool _isValidPassword(String s) => RegExp(r'^(?=.*[A-Za-z])(?=.*\d).{6,20}$').hasMatch(s);

  Future<void> _doLogin(AuthStore auth) async {
    final phone = _loginPhoneController.text.trim();
    final password = _loginPasswordController.text.trim();
    if (!_isValidPhone(phone)) {
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('请输入有效的手机号')));
      return;
    }
    if (!_isValidPassword(password)) {
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('密码需6-20位，包含字母与数字')));
      return;
    }
    setState(() => _loading = true);
    try {
      await auth.loginRemote(phone: phone, password: password, deviceType: CommonUtils.versionPlatformParam());
      if (mounted) Navigator.of(context).pop();
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('$e')));
    } finally {
      if (mounted) setState(() => _loading = false);
    }
  }

  Future<void> _doRegister(AuthStore auth) async {
    final phone = _regPhoneController.text.trim();
    final username = _regUsernameController.text.trim();
    final password = _regPasswordController.text.trim();
    if (!_isValidUsername(username)) {
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('用户名2-20位，仅字母、数字、下划线')));
      return;
    }
    if (!_isValidPassword(password)) {
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('密码需6-20位，包含字母与数字')));
      return;
    }
    if (!_isValidPhone(phone)) {
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('请输入有效的手机号')));
      return;
    }
    setState(() => _loading = true);
    try {
      await auth.registerRemote(username: username, password: password, phone: phone);
      if (mounted) Navigator.of(context).pop();
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('$e')));
    } finally {
      if (mounted) setState(() => _loading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    final auth = Provider.of<AuthStore>(context);
    return Scaffold(
      appBar: AppBar(title: const Text('登录/注册')),
      body: Center(
        child: ConstrainedBox(
          constraints: const BoxConstraints(maxWidth: 420),
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                Row(
                  children: [
                    Expanded(
                      child: OutlinedButton(
                        onPressed: () => setState(() => _tab = 0),
                        child: const Text('登录'),
                      ),
                    ),
                    const SizedBox(width: 8),
                    Expanded(
                      child: OutlinedButton(
                        onPressed: () => setState(() => _tab = 1),
                        child: const Text('注册'),
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 16),
                if (_tab == 0)
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      TextField(
                        controller: _loginPhoneController,
                        keyboardType: TextInputType.phone,
                        decoration: const InputDecoration(labelText: '手机号'),
                      ),
                      const SizedBox(height: 12),
                      TextField(
                        controller: _loginPasswordController,
                        obscureText: true,
                        decoration: const InputDecoration(labelText: '密码'),
                      ),
                      const SizedBox(height: 12),
                      ElevatedButton(
                        onPressed: _loading ? null : () => _doLogin(auth),
                        child: _loading ? const SizedBox(height: 20, width: 20, child: CircularProgressIndicator(strokeWidth: 2)) : const Text('登录'),
                      ),
                    ],
                  )
                else
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      TextField(
                        controller: _regPhoneController,
                        keyboardType: TextInputType.phone,
                        decoration: const InputDecoration(labelText: '手机号'),
                      ),
                      const SizedBox(height: 12),
                      TextField(
                        controller: _regUsernameController,
                        decoration: const InputDecoration(labelText: '用户名'),
                      ),
                      const SizedBox(height: 12),
                      TextField(
                        controller: _regPasswordController,
                        obscureText: true,
                        decoration: const InputDecoration(labelText: '密码'),
                      ),
                      const SizedBox(height: 12),
                      ElevatedButton(
                        onPressed: _loading ? null : () => _doRegister(auth),
                        child: _loading ? const SizedBox(height: 20, width: 20, child: CircularProgressIndicator(strokeWidth: 2)) : const Text('注册'),
                      ),
                    ],
                  ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
